var SelectIndustryModal = {
  selectedIndustries: [],
  maxSelected: 0,
  callback: $.noop,

  init: function() {
    $('#select_industry_modal').on('shown', function() {
      SelectIndustryModal.selectedIndustries = [];
      $('#select_industry_modal_selected').empty();
      $('#select_industry_modal_options :checkbox').removeAttr('checked');
      // 取得传入的行业参数并选中
      var selectedIds = $('#select_industry_modal').data('selectedIds');
      if (selectedIds) {
        for (var i = 0; i < selectedIds.length; i++) {
          SelectIndustryModal._selectIndustry(selectedIds[i]);
        }
      }
      SelectIndustryModal.maxSelected = $('#select_industry_modal').data('maxSelected');
      SelectIndustryModal.callback = $('#select_industry_modal').data('callback') || $.noop;
    }).modal({ show: true });

    $('#select_industry_modal_ok').on('click', function() {
      $('#select_industry_modal').modal('hide');
      // 取得选中的行业并回填
      SelectIndustryModal.callback(SelectIndustryModal.getSelectedIndustries());
    });

    $('#select_industry_modal_options :checkbox').unbind('click').click(function(event) {
      if ($(this).attr('checked')) {
        if (SelectIndustryModal.selectedIndustries.length === SelectIndustryModal.maxSelected) {
          window.alert('对不起，您最多只能选择' + SelectIndustryModal.maxSelected + '项。');
          $(this).removeAttr('checked');
          return;
        }
        SelectIndustryModal._selectIndustry($(this).val());
      } else {
        SelectIndustryModal._removeSelectedIndustry($(this).val());
      }
    });

    $('#select_industry_modal_selected :checkbox').die('click').live('click', function(event) {
      var id = $(this).val();
      SelectIndustryModal._removeSelectedIndustry(id);
      $('#select_industry_modal_option_' + id + ' :checkbox').removeAttr('checked');
    });
  },

  getSelectedIndustries: function() {
    return SelectIndustryModal.selectedIndustries;
  },

  _selectIndustry: function(id) {
    if (id) {
      var option = $('#select_industry_modal_option_' + id);
      if (option.length) {
        option.children(':checkbox').attr('checked', 'true');
        option.clone().attr('id', 'select_industry_modal_selected_' + id).appendTo($('#select_industry_modal_selected'));
        SelectIndustryModal.selectedIndustries.push({ id: id, name: $.trim(option.text()) });
      }
    }
  },

  _removeSelectedIndustry: function(id) {
    for (var i = SelectIndustryModal.selectedIndustries.length - 1; i >= 0; i--) {
      if (SelectIndustryModal.selectedIndustries[i].id === id) {
        SelectIndustryModal.selectedIndustries.splice(i);
        break;
      }
    }
    $('#select_industry_modal_selected :checkbox[value="' + id + '"]').parent().remove();
  }
};
